package com.mobile.socketclient;

import android.util.Log;

import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;

public class SocketNotifyServer {
    // socket服务
    ServerSocket serverSocket = null;
    // 用来存放已连接的客户端的socket会话
    static volatile Map<Integer, Socket> sessionMap = Collections.synchronizedMap(new HashMap<>());
    private static final String TAG = "SocketNotifyServer";

    public void socket() {
        new Thread(() -> {
            try {
                // 创建serverSocket，绑定端口为8888
                serverSocket = new ServerSocket(8888);
                Log.e(TAG,"服务器开启。。。");
                // 客户端编号
                int i = 1;
                // 实现多个客户端连接
                while (true) {
                    //一直等待链接
                    Socket socket = serverSocket.accept();
                    Log.e(TAG,"客户端" + i + "连接成功。。。");
                    if (socket != null) {
                        // 将socket放入map，key为客户端编号
                        sessionMap.put(i, socket);
                        Log.e(TAG, "sessionMap put了一个socket");
                        // 开启线程处理本次会话
                        Thread thread = new Thread(new NotifyHandler(socket, sessionMap));
                        thread.setDaemon(true);
                        thread.start();
                        i++;
                    }
                }
            } catch (IOException e) {
                e.printStackTrace();
                Log.e(TAG, "服务端发现关闭流了0");
            }
        }).start();
    }

    public void onDestroy() {
        try {
            serverSocket.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}
